<script setup lang="ts">
import { navigate } from '@/utils/navigate';
import { useAppStore, useControllerStore } from '@/store';
import HomeRequest from '@/request/homeRequest';
import to from '@/utils/to';
import useToast from '@/hooks/useToast';
import Tools from '@/utils/tools';
import ShoppingCart from '@/subcontract/home/component/ShoppingCart.vue';
import SkuSelectionPopup from '@/subcontract/home/component/SkuSelectionPopup.vue';
import SkuPackageSelectionPopup from '@/subcontract/home/component/SkuPackageSelectionPopup.vue';

interface IState {
  data?: IProductInformation;
  shoppingCartProduct?: IProductInformation;
  shoppingCart: IProductInformation[];
  current: number;
  swiperItem: IProductInformation['goodsImages'];
  shoppingCartShow: boolean;
}

const store = useAppStore();
const state = reactive<IState>({ shoppingCartShow: false, shoppingCart: store.$state.shoppingCart, swiperItem: [], current: 0 });
const { showToast } = useToast();
const instance = getCurrentInstance();

onLoad(async (options) => {
  if (!options || !options.product) {
    showToast('产品错误，请联系客服');
    navigate({ type: 'navigateBack', url: '' });
    return;
  }
  const product = JSON.parse(decodeURIComponent(options.product)) as IProductInformation;
  const [err, res] = await to(HomeRequest.ObtainProductDetails({ id: product.goodsId, hasLoading: true }));
  if (err) return;
  state.data = { ...res.data, active: product.active };
  state.shoppingCartProduct = state.shoppingCart.find((_item) => _item.goodsId === res.data.goodsId);
  if (state.data.goodsImages && state.data.goodsImages.length > 0) {
    state.swiperItem.push(...state.data.goodsImages.filter((item) => item.type === 2));
    state.swiperItem.push(...state.data.goodsImages.filter((item) => item.type === 1));
    if (state.swiperItem[0].type === 2) uni.createVideoContext('videoSwiper0', instance).play();
  }
  // 由首页选购产品进入的添加购物车或选择规格操作
  if (options.hasHomePath) {
    if (options.hasSku === 'true') {
      handleMultiSpecSelPopupVisible();
    } else {
      handleOperationProductToShoppingCart('add', state.data);
      state.shoppingCartShow = true;
    }
  }
});

onUnmounted(() => {
  unsubscribe();
});

// store全局监听
const unsubscribe = store.$subscribe((mutation, storeState) => {
  if (Array.isArray(mutation.events)) return;
  if (mutation.events.key === 'shoppingCart') {
    state.shoppingCart = storeState.shoppingCart;
    state.shoppingCartProduct = storeState.shoppingCart.find((_item) => _item.goodsId === state.data!.goodsId);
  }
});

// 打开多规格选择弹窗
const handleMultiSpecSelPopupVisible = () => {
  useControllerStore().$patch({ productInformation: state.data });
  if (state.data!.goodsType === 2) {
    useControllerStore().$patch({ skuPackageSelectionPopup: true });
  } else {
    useControllerStore().$patch({ skuSelectionPopup: true });
  }
};

// 收藏或者取消收藏产品
const handleCollectOrCancelProd = () => {
  const { goodsId, collect } = state.data!;
  HomeRequest.CollectOrCancelProd({ state: collect ? 0 : 1, goodsId, collectType: 1, hasLoading: true }).then(() => {
    showToast(collect ? '取消收藏成功' : '收藏成功');
    state.data = { ...state.data!, collect: collect ? 0 : 1 };
  });
};

// 添加产品购物车
const handleOperationProductToShoppingCart = (type: 'add' | 'remove', data: IProductInformation) => {
  store.updateShoppingCart({ type, data });
};

// 处理swiper change事件
const handleSwiperChange = (e: any) => {
  state.current = e.detail.current;
  if (state.swiperItem[state.current].type === 2) {
    const videoContext = uni.createVideoContext(`videoSwiper${state.current}`, instance);
    videoContext.play();
  }
  if (state.swiperItem[state.current - 1].type === 2) {
    const videoContext = uni.createVideoContext(`videoSwiper${state.current - 1}`, instance);
    videoContext.pause();
    videoContext.seek(0);
  }
};
</script>

<template>
  <view v-if="state.data" class="overflow-scroll" :style="{ height: `calc(100vh - ${store.$state.tabbarHeight}px)` }">
    <view class="pos-relative w-full h-280px">
      <swiper :autoplay="false" class="h-full" :indicator-dots="state.data.goodsImages.length > 1" indicator-active-color="#ffc300" @change="handleSwiperChange">
        <swiper-item v-for="(item, index) in state.swiperItem" :key="index">
          <video v-if="item.type === 2" :id="`videoSwiper${state.current}`" class="w-full h-full" loop :src="item.url" :enable-progress-gesture="false" enable-play-gesture></video>
          <image v-else class="w-full h-full" :src="item.url" mode="aspectFill" />
        </swiper-item>
      </swiper>
      <view class="pos-absolute top-0 left-0" :style="{ paddingTop: `${store.$state.menuInfo.top}px`, height: store.$state.menuInfo.height + 8 + 'px', paddingRight: store.$state.menuInfo.width + 12 + 'px' }">
        <i class="i-mingcute:left-fill text-[28px]" @click="navigate({ type: 'navigateBack', url: '' })" />
      </view>
    </view>
    <view class="c-pd bg-white mb-12px">
      <view class="flex justify-between items-center">
        <text class="fw-bold c-text-16">{{ state.data.name }}</text>
        <view class="flex flex-col text-align-center" @click="handleCollectOrCancelProd">
          <i class="text-18px c-color" :class="state.data.collect > 0 ? 'i-mynaui:star-solid ' : 'i-mynaui:star'" />
          <text class="c-text-8 c-text-color-grey mt-2px">收藏</text>
        </view>
      </view>
      <view class="my-8px">
        <RenderProductDiscount :data="state.data" />
      </view>
      <view class="flex justify-between items-center">
        <view class="flex items-center">
          <RenderProductPrice v-if="Tools.renderProductValidation(state.data) > 2" :data="state.data" />
          <text v-if="state.data.packageFee > 0" class="c-text-color-grey c-text-10 mr-8px">包装费：¥{{ state.data.packageFee }}</text>
        </view>
        <view>
          <text v-if="Tools.renderProductValidation(state.data) <= 2" class="c-text-color-grey">{{ Tools.renderProductValidation(state.data) === 1 ? '非可售时间' : '已售罄' }}</text>
          <view v-if="Tools.renderProductValidation(state.data) === 3" class="inline c-bg c-br px-8px py-1px text-white c-text-12" @click.stop="handleMultiSpecSelPopupVisible"> 选规格 </view>
          <view v-if="Tools.renderProductValidation(state.data) === 4" class="inline-flex items-center">
            <i v-if="state.shoppingCartProduct" class="i-gg:remove c-color c-text-16" @click.stop="handleOperationProductToShoppingCart('remove', state.data)" />
            <text v-if="state.shoppingCartProduct" class="mx-8px fw-bold c-text-14">{{ state.shoppingCartProduct.nums }}</text>
            <i class="i-icon-park-solid:add-one c-color c-text-16" @click.stop="handleOperationProductToShoppingCart('add', state.data)" />
          </view>
        </view>
      </view>
    </view>
    <view class="c-pd bg-white mb-12px">
      <view class="flex">
        <view class="w-100px mr-8px c-text-color-grey">商户名称：</view>
        <view class="flex-1">{{ state.data.businessName }}</view>
      </view>
      <view class="flex mt-8px">
        <view class="w-100px mr-8px c-text-color-grey">商户分类：</view>
        <view class="flex-1">{{ state.data.thirdClassifyName }}</view>
      </view>
      <view class="flex mt-8px">
        <view class="w-100px mr-8px c-text-color-grey">简介：</view>
        <view class="flex-1">{{ state.data.introduce }}</view>
      </view>
      <view class="flex mt-8px">
        <view class="w-100px mr-8px c-text-color-grey">商家咨询：</view>
        <view class="flex-1 text-red flex items-center" @click="Tools.callPhone(state.data.businessPhone)">拨打电话 <i class="i-gg:phone ml-4px" /></view>
      </view>
      <view class="flex mt-8px" v-if="state.data.goodsHours && state.data.goodsHours.length > 0">
        <view class="w-100px mr-8px c-text-color-grey">可售时间：</view>
        <view class="flex-1 text-red">
          <view v-for="(item, index) in state.data.goodsHours" :key="index"> {{ item.beginHours }}-{{ item.endHours }} </view>
        </view>
      </view>
    </view>
    <van-divider contentPosition="center" v-if="state.data.describes">详情</van-divider>
    <view class="c-pd bg-white mb-12px">
      <UvParse :content="state.data.describes" />
    </view>
  </view>
  <SkuSelectionPopup />
  <SkuPackageSelectionPopup />
  <ShoppingCart v-if="state.data" :show="state.shoppingCartShow" />
</template>
